package com.bite.messageQueue.mqServer.datacenter;

import com.bite.messageQueue.common.MqException;
import com.bite.messageQueue.mqServer.core.Binding;
import com.bite.messageQueue.mqServer.core.Exchange;
import com.bite.messageQueue.mqServer.core.MSGQueue;
import com.bite.messageQueue.mqServer.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 使用这个类来管理所有硬盘上的数据
 * 1.数据库：交换机，队列，绑定
 * 2.数据文件：消息
 */
public class DiskDataCenter {
    private DataBaseManager dataBaseManager = new DataBaseManager();
    private MessageFileManager messageFileManager = new MessageFileManager();

    /**
     *  实例初始化数据库和数据文件
     */
    public void init(){
        dataBaseManager.init();
        messageFileManager.init();
    }

    /**
     * 封装交换机操作
     * @param exchange 交换机
     */
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }

    /**
     * 封装队列操作
     * @param queue 队列
     */
    public void insertQueue(MSGQueue queue) throws IOException {
        messageFileManager.createQueue(queue.getName());
        dataBaseManager.insertQueue(queue);
    }

    public void deleteQueue(String queueName){
        dataBaseManager.deleteQueue(queueName);
    }

    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueues();
    }

    /**
     * 封装绑定操作
     * @param binding 绑定
     */
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBindings();
    }

    /**
     * 封装消息操作
     * @param message 消息
     */
    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue, message);
    }

    public void deleteMessage(MSGQueue queue, Message message) throws IOException, MqException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue, message);
        //删除后如果需要，则进行垃圾回收
        if(messageFileManager.checkGC(queue.getName())){
            messageFileManager.GC(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
